import React, { PureComponent } from 'react';
import { connect } from 'dva';
import myStyle from './index.less';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Popconfirm, message } from 'antd';
import { TableC, SelectC, PrimaryC, NestedTableC, PrimaryGhostC, InputNumberC, FirstHeaderC, TreeSelectC } from '../../../../comps';
import { fixedNum, isRepeat } from '../../../../utils/utils';
import _ from 'lodash';
import { isZiGuanEvir } from '../../../../utils/commonFunc';
import uuid from 'es6-uuid';

@Form.create()
class SplitTableBankC extends PureComponent {
  state = {
    tradeInfoDs: [], // 交易信息的表格
    dataSource: [], // 表格数据源
    currentRow: undefined, // 正在编辑的行 之前的数据
    editFlag: false, // 编辑状态
    selectedRowKeys: [], // 已选中项
    childSelectData: [], // 融券回购子表格质押券下拉
    selectObj: {}, // 存入每个产品组合的质押券的下拉数组
  };

  componentDidMount() {
    this.props.onRef(this);
    const { isDetail } = this.props;
    const data = _.cloneDeep(this.props.tradeInfo.zgPledgeVo || []);
    const arr = [];
    this.setState({
      expandedKeys: this.props.dataSource.map((item) => item.key), // 设置展开行keys集合
    });
    data.map((item) => {
      arr.push({
        value: item.id,
        title: `${item.tradingcode  }-${  item.secuabbr}`,
      });
    });
    data.map((item) => {
      item.ratio = isDetail ? '100.00%' : '0.00%';
      item.assignAmount = isDetail ? parseInt(item.pledgeAmount) : 0;
    });
    this.setState(
      {
        dataSource: _.cloneDeep(this.props.dataSource),
        tradeInfoDs: [...data],
        childSelectData: [...arr],
      },
      () => {
        if (isDetail) return; // 详情时直接加载查询到的数据即可
        if (this.props.tradeInfo.direction == 1) {
          // 融券回购子表为交易信息的数据
          this.getChildTable();
        } else {
          // 融资回购子表 质押券下拉处理
          this.getSelectList();
        }
      },
    );
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (JSON.stringify(this.props.dataSource) != JSON.stringify(nextProps.dataSource)) {
      this.setState({
        expandedKeys: nextProps.dataSource.map((item) => item.key), // 设置展开行keys集合
      });
      this.setState(
        {
          dataSource: _.cloneDeep(nextProps.dataSource),
        },
        () => {
          if (this.props.isDetail) return; // 详情时直接加载查询到的数据即可
          if (this.props.tradeInfo.direction == 1) {
            // 融券回购子表为交易信息的数据
            this.getChildTable();
          } else {
            // 融资回购子表 质押券下拉处理
            this.getSelectList();
          }
        },
      );
    }
  }

  getSelectList = () => {
    // 融资回购子表 质押券下拉处理
    const { dataSource } = this.state;
    const obj = {};
    dataSource &&
      dataSource.map((item, key) => {
        const temp = item.nestedConfig.dataSource;
        const treeData = _.cloneDeep(
          temp.map((item) => {
            return { value: item.id, title: item.name };
          }),
        );
        obj[item.key] = treeData;
        this.setState({
          // 将每个产品组合的质押券下拉 保存起来
          selectObj: { ...this.state.selectObj, ...obj },
        });
      });
  };

  // 准备融券回购 子表数据
  getChildTable = (type) => {
    const { dataSource, tradeInfoDs, expandedKeys } = this.state;
    const { holdList = [] } = this.props;
    const arr = [];
    tradeInfoDs.map((item) => {
      // 质押数量同交易信息表格中的质押数量，交易数量和交易金额为0；
      const obj = {};
      obj.tradeNum = 0;
      obj.tradePrice = 0;
      obj.name = `${item.tradingcode  }-${  item.secuabbr}`;
      obj.isEdit = false;
      obj.key = uuid(32);
      obj.id = item.id;
      obj.tradingcode = item.tradingcode;
      obj.pledgeAmount = item.pledgeAmount;
      obj.secuabbr = item.secuabbr;
      arr.push(obj);
    });

    const nestedConfig = {
      columns: this.childColumns(),
      dataSource: arr,
      rowKey: 'key',
    };
    if (type == 'add') {
      const obj = {
        isEdit: true,
        key: uuid(32),
        tradeNum: 0,
        tradePrice: 0,
        nestedConfig,
      };
      expandedKeys.push(obj.key); // 展开行设置
      dataSource.unshift(obj);
      this.setState({
        expandedKeys: [...expandedKeys],
      });
    }
    dataSource.map((item, index) => {
      item.isEdit = false;
      if (index == 0 && type == 'add') item.isEdit = true;
      nestedConfig.dataSource.map((child) => {
        child.pid = item.key;
        holdList.map((hold) => {
          // 持仓数量
          if (hold.fundId == item.productId && hold.tradingcode == child.tradingcode) {
            child.available = hold.available;
            child.hold = hold.hold;
          }
        });
      });
      if ((index == 0 && type == 'add') || !type) item.nestedConfig = _.cloneDeep(nestedConfig);
    });

    this.setState({
      dataSource: [...dataSource],
    });
  };

  // 用户点击确定
  submit = () => {
    const { dataSource, ratio, assignFee, tradeInfoDs } = this.state;
    const { tradeInfo } = this.props;
    if (!dataSource.length) {
      message.warning('请先新增数据');
      return;
    }
    for (let index = 0; index < dataSource.length; index++) {
      const item = dataSource[index];
      if (item.isEdit) {
        message.warning('请先保存正在编辑的数据');
        return;
      }
      const children = item.nestedConfig ? item.nestedConfig.dataSource || [] : [];
      if (!children.length) {
        message.warning('请删除交易金额为0的数据');
        return;
      }
      for (let j = 0; j < children.length; j++) {
        const child = children[j];
        if (child.isEdit) {
          message.warning('请先保存正在编辑的数据');
          return;
        }
        if (child.tradeNum == 0) {
          message.warning('请删除交易数量为0的数据');
          return;
        }
      }
    }
    for (let k = 0; k < tradeInfoDs.length; k++) {
      const trade = tradeInfoDs[k];
      if (trade.assignAmount !== Number(trade.pledgeAmount)) {
        message.warning('交易信息表中的各质押券已分配比例必须100%');
        return;
      }
    }
    if (tradeInfo.fee && assignFee != tradeInfo.fee) {
      // 有尾差，最后一个组合中加入尾差，即表格中的费用之和等于交易信息的费用
      dataSource[dataSource.length - 1].fee = dataSource[dataSource.length - 1].fee + (tradeInfo.fee - assignFee);
      this.setState({
        dataSource: [...dataSource],
        assignFee: tradeInfo.fee,
      });
      this.props.feeChange(tradeInfo.fee); // 抛出已分配费用
    }
    return dataSource;
  };

  // 质押券变更
  onChangeTradingCode = (e, option, record) => {
    const { dataSource, tradeInfoDs } = this.state;
    // 选择质押券（质押券的下拉数据为交易信息表格中的质押券），
    // 回填【持仓数量】【可用数量】【质押券数量】，【交易数据量】和【交易金额】默认为0，用户可输入【交易数量】；
    const tradingcode = option.props.children ? option.props.children.split('-')[0] : '';
    let parentRow;
    dataSource.map((x) => {
      if (x.key == record.pid) {
        parentRow = { ...x };
        x.nestedConfig.dataSource.map((item) => {
          // 对应的其他属性
          if (item.key == record.key) {
            item.id = e;
            item.tradingcode = tradingcode;
            item.tradeNum = 0;
            item.tradePrice = 0;
            if (option) item.name = option.props ? option.props.children : undefined;
            tradeInfoDs.map((trade) => {
              // 查询【质押数量】
              if (trade.tradingcode == tradingcode) {
                item.pledgeAmount = trade.pledgeAmount;
                item.secuabbr = trade.secuabbr; // 需要简称 后端使用
              }
            });
            this.props.holdList.map((hold) => {
              // 持仓数量
              if (hold.fundId == x.productId && hold.tradingcode == item.tradingcode) {
                item.available = hold.available;
                item.hold = hold.hold;
              }
            });
          }
        });
      }
    });
    this.setState({
      dataSource: [...dataSource],
    });
  };

  // 交易数量变更
  onChangeTradeNum = (e, record) => {
    const { dataSource, tradeInfoDs } = this.state;
    const { tradeInfo } = this.props;
    if (typeof e !== 'number') return;
    let feeNumSum = 0;
    dataSource.map((x) => {
      if (x.key == record.pid) {
        let myTradePriceSum = 0; // 父节点的【交易金额】等于子节点【交易金额】总和；
        x.nestedConfig.dataSource.map((item) => {
          // 对应的其他属性
          if (item.key == record.key) {
            item.tradeNum = e;
            // 实时计算【交易金额】=交易数量*100*折算率；
            if (item.tradingcode) {
              const arr = tradeInfoDs.filter((x) => item.id == x.id);
              item.tradePrice = arr[0] ? arr[0].pledgeRatio * e : 0;
            }
          }
          myTradePriceSum += item.tradePrice;
        });
        x.tradePrice = myTradePriceSum;
      }
      if (tradeInfo.fee && tradeInfo.repurchaseAmount) {
        // 费用（表格中组合费用）】= 交易金额（组合）/回购金额*费用（交易信息中的总费用），
        x.fee = (x.tradePrice / (tradeInfo.repurchaseAmount || 0)) * tradeInfo.fee;
        x.fee = Number(x.fee.toFixed(2));
        feeNumSum += x.fee !== undefined && x.fee !== null ? x.fee : 0; // 计算已分配费用
      }
    });
    this.props.feeChange(Number(feeNumSum.toFixed(2))); // 抛出已分配费用
    this.setState({
      dataSource: [...dataSource],
      assignFee: Number(feeNumSum.toFixed(2)),
    });
  };

  // 计算已分配比例/数量 已分配费用
  calcAssign = () => {
    const { dataSource, tradeInfoDs } = this.state;
    const { tradeInfo } = this.props;
    let feeNumSum = 0;
    dataSource.map((x) => {
      if (tradeInfo.fee) {
        feeNumSum += x.fee !== undefined && x.fee !== null ? x.fee : 0; // 计算已分配费用
      }
    });
    this.props.feeChange(feeNumSum.toFixed(2)); // 抛出已分配费用
    this.setState({
      assignFee: Number(feeNumSum.toFixed(2)),
    });
    tradeInfoDs.map((item) => {
      let sum = 0;
      dataSource.map((x) => {
        let childsum = 0;
        x.nestedConfig &&
          x.nestedConfig.dataSource.map((child) => {
            if (item.id == child.id) {
              childsum += child.tradeNum || 0;
            }
          });
        sum += childsum;
      });
      item.assignAmount = sum;
      item.ratio = `${parseFloat((item.assignAmount / (Number(item.pledgeAmount))) * 100).toFixed(2)  }%`;
    });
    this.setState({
      tradeInfoDs: [...tradeInfoDs],
    });
  };

  // 添加子表质押券
  addChildRow = (record) => {
    const { dataSource, editFlag, expandedKeys } = this.state;
    if (editFlag) {
      message.warning('每次只能编辑一条数据！');
      return;
    }
    this.setState({
      editFlag: true,
    });
    dataSource.map((item) => {
      if (item.key === record.key) {
        // 并且添加一条质押券，若已有子表格，则在子表格第一行插入一行编辑状态的数据，若无子表格，则构建表格，并且在第一行插入编辑状态的数据；
        const currentChild = item.nestedConfig ? item.nestedConfig.dataSource : [];

        const obj = {
          tradeNum: 0,
          tradePrice: 0,
          isEdit: true,
          isAdd: true,
          key: uuid(32),
          pid: item.key,
        };
        currentChild.unshift(obj);

        if (item.nestedConfig) item.nestedConfig.dataSource = [...currentChild];
        else {
          item.nestedConfig = { columns: this.childColumns() };
          item.nestedConfig.dataSource = [...currentChild];
        }
      }
    });
    this.setState({
      dataSource: [...dataSource],
    });
  };

  // 产品组合变更
  onChangeProduct = (e, option, record) => {
    const { dataSource } = this.state;
    dataSource.map((item) => {
      // 对应的其他属性
      if (item.key == record.key) {
        item.productId = e;
        if (option) item.name = option[0];
        if (this.props.tradeInfo.direction == 1)
          item.nestedConfig.dataSource.map((child) => {
            this.props.holdList.map((hold) => {
              // 持仓数量
              if (hold.fundId == item.productId && hold.tradingcode == child.tradingcode) {
                child.available = hold.available;
                child.hold = hold.hold;
              }
            });
          });
      }
      this.props.fundList &&
        this.props.fundList.map((x) => {
          // 新增的条目 可用金额不变
          if (x.nodeId == item.productId) {
            item.t0 = x.t0;
            item.t1 = x.t1;
          }
        });
    });
    this.setState(
      {
        dataSource: [...dataSource],
      },
      () => {
        if (record.productId && this.props.tradeInfo.direction == 2) this.onNestedExtend(true, record, 'flag');
      },
    );
  };

  // 拆分表格
  renderTable = () => {
    const { loading, isDetail, settlement } = this.props;
    const width = isDetail ? (settlement ? 190 : 240) : 160;
    const columns = [
      {
        title: '产品组合',
        key: 'productId',
        width: 196,
        render: (text, record, index) => {
          if (!record.isEdit) {
            return (
              <span title={record.name} style={{ display: 'inline-block', width: '180px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
                {record.name === null || record.name === undefined ? '--' : record.name}
              </span>
            );
          }
          if (record.isEdit) {
            return (
              <TreeSelectC
                form={this.props.form} // form对象
                dataIndex={'productId'} // Form识别的Item ID
                dataSource={this.props.portfolioTree}
                onChange={(e, option) => this.onChangeProduct(e, option, record)}
                initialValue={record.productId}
                treeDefaultExpandAll={true}
                positionBody={true}
              />
            );
          }
        },
      },
      { title: 'T+0可用', key: 't0', type: 'money', width },
      { title: 'T+1可用', key: 't1', type: 'money', width },
      { title: '交易金额', key: 'tradePrice', type: 'money', width },
      { title: '费用', key: 'fee', type: 'number', width: settlement ? width : undefined },
    ];
    if (settlement) {
      columns.push({ title: '交收状态', key: 'instructionStatus' });
    }
    if (!this.props.isDetail) {
      if (columns && columns[columns.length - 1].key != 'operate') {
        columns.push({
          title: '操作',
          dataIndex: 'operate',
          key: 'operate',
          type: 'operate',
          // fixed:"right",
          width: 180,
          operates: [
            {
              title: '保存',
              onClick: (record, index) => this.saveRow(record),
              rules: {
                hide: { relation: 'and', items: [{ key: 'isEdit', value: [false], relation: ['='] }] },
              },
            },
            {
              title: '取消',
              onClick: (record, index) => this.cancelRow(record.key),
              rules: {
                hide: { relation: 'and', items: [{ key: 'isEdit', value: [false], relation: ['='] }] },
              },
            },
            {
              title: '添加质押券',
              onClick: (record, index) => this.addChildRow(record),
              rules: {
                hide: { relation: 'and', items: [{ key: 'isEdit', value: [true], relation: ['='] }] },
              },
            },
            {
              title: '删除',
              onClick: (record, index) => this.deleteRow(record.key),
              rules: {
                hide: { relation: 'and', items: [{ key: 'isEdit', value: [true], relation: ['='] }] },
              },
            },
          ],
        });
      }
    }
    const rowSelection = {
      onChange: (selectedRowKeys) => {
        this.setState({
          selectedRowKeys,
        });
      },
    };
    return (
      <NestedTableC
        rowKey='key'
        scroll={{ x: '100%' }}
        columns={columns}
        hidePage={true}
        expandedRowKeys={this.state.expandedKeys} // 展开的行
        scroll={{ y: window.innerHeight - 740 < 240 ? 240 : window.innerHeight - 740 }}
        dataSource={this.state.dataSource}
        commonHeader={false}
        loading={this.props.loadingStatus == true || loading.effects['orderSplitM/querySplitTableList2'] == true}
        rowSelection={rowSelection}
        defaultExpandAllRows={true}
        onExpand={this.onExpand}
      />
    );
  };

  onExpand = (expanded, record) => {
    // 为了控制展开 关闭弹窗
    let keys = this.state.expandedKeys || [];
    if (expanded) {
      // 展开的时候 加入
      keys.push(record.key);
    } else {
      // 关闭的时候 去除
      if (keys.length) {
        keys = keys.filter((v) => {
          return v != record.key;
        });
      }
    }
    this.setState({ expandedKeys: [...keys] });
  };

  // 选中之后 请求后端 确定子表
  onNestedExtend = (expanded, record, type) => {
    const { dispatch, tradeInfo } = this.props;
    const { tradeInfoDs, dataSource } = this.state;
    const index = dataSource.findIndex((item) => item.key === record.key && item.productId);
    if (index > -1 && expanded) {
      const arr = [];
      tradeInfoDs.map((item) => {
        // 质押数量同交易信息表格中的质押数量，交易数量和交易金额为0；
        const obj = {};
        obj.tradeNum = 0;
        obj.tradePrice = 0;
        obj.name = `${item.tradingcode  }-${  item.secuabbr}`;
        obj.isEdit = false;
        obj.key = uuid(32);
        obj.id = item.id;
        obj.tradingcode = item.tradingcode;
        obj.pledgeAmount = item.pledgeAmount;
        obj.secuabbr = item.secuabbr;
        arr.push(obj);
      });
      // 这里写逻辑，处理数据
      if (type == 'flag') {
        dataSource[index].loading = true;
        dispatch({
          type: 'orderSplitM/queryHold',
          payload: {
            portfolio: record.productId,
            trustee: tradeInfo.clientCode,
            currentPage: 1,
            numInPage: 9999,
          },
          callback: (data) => {
            if (data) {
              const temp = [];
              arr.map((item) => {
                data.map((x) => {
                  if (item.name == x.name) {
                    temp.push(item);
                  }
                });
              });
              const treeData = _.cloneDeep(
                temp.map((item) => {
                  return { value: item.id, title: item.name };
                }),
              );
              dataSource[index].loading = false;
              const oldArr = dataSource[index].nestedConfig?.dataSource || [];
              oldArr[0] && oldArr[0].isAdd ? temp.unshift(oldArr[0]) : null; // 点击了添加质押券之后 点击展开
              dataSource[index].nestedConfig = {
                rowKey: 'key',
                columns: this.childColumns(),
                dataSource: temp,
                hidePage: true,
              };
              dataSource.map((item, key) => {
                if (key == index) {
                  const obj = { [item.key]: treeData };
                  this.setState({
                    // 将每个产品组合的质押券下拉 保存起来
                    selectObj: { ...this.state.selectObj, ...obj },
                  });
                  item.nestedConfig.dataSource.map((child) => {
                    child.pid = item.key;
                    this.props.holdList.map((hold) => {
                      // 持仓数量
                      if (hold.fundId == item.productId && hold.tradingcode == child.tradingcode) {
                        child.available = hold.available;
                        child.hold = hold.hold;
                      }
                    });
                  });
                }
              });
              this.setState({
                dataSource: [...dataSource],
              });
            } else {
              dataSource[index].loading = false;
            }
          },
        });
      }
    }
  };

  // 字表的columns
  childColumns = () => {
    const { isDetail, tradeInfo, settlement } = this.props;
    const { childSelectData } = this.state;
    const width = isDetail ? 190 : 160;
    const columns = [
      {
        title: '质押券',
        key: 'id',
        width: isDetail ? 190 : 170,

        render: (text, record, index) => {
          if (!record.isAdd) {
            return (
              <span
                title={record.name}
                style={{ display: 'inline-block', width: isDetail ? '164px' : '144px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}
              >
                {record.name === null || record.name === undefined ? '--' : record.name}
              </span>
            );
          }
          if (record.isAdd) {
            return (
              <SelectC
                form={this.props.form} // form对象
                dataIndex={'id'} // Form识别的Item ID
                dataSource={tradeInfo.direction == 1 ? childSelectData : this.state.selectObj[record.pid] || []}
                onChange={(e, option) => this.onChangeTradingCode(e, option, record)}
                initialValue={record.id}
              />
            );
          }
        },
      },
      { title: '持仓数量', key: 'hold', type: 'number', width },
      { title: '可用数量', key: 'available', type: 'number', width },
      { title: '质押数量', key: 'pledgeAmount', type: 'number', width },
      {
        title: '交易数量',
        key: 'tradeNum',
        align: 'right',
        width,
        render: (text, record, index) => {
          if (!record.isEdit) {
            return <span>{text === undefined ? '--' : fixedNum(text, 0)}</span>;
          }
          if (record.isEdit) {
            return (
              <InputNumberC
                form={this.props.form} // form对象
                dataIndex={'tradeNum'}
                initialValue={record.tradeNum}
                splitStyle={true}
                onChange={(e) => {
                  this.onChangeTradeNum(e, record);
                }}
                min={0}
                // unit={"股"}
              />
            );
          }
        },
      },
      { title: '交易金额', key: 'tradePrice', type: 'money' },
    ];

    if (!this.props.isDetail) {
      if (columns && columns[columns.length - 1].key != 'operate') {
        columns.push({
          title: '操作',
          dataIndex: 'operate',
          key: 'operate',
          type: 'operate',
          // fixed:"right",
          width: 150,
          operates: [
            {
              title: '保存',
              onClick: (record, index) => this.saveChildRow(record),
              rules: {
                hide: { relation: 'and', items: [{ key: 'isEdit', value: [false], relation: ['='] }] },
              },
            },
            {
              title: '取消',
              onClick: (record, index) => this.cancelChildRow(record),
              rules: {
                hide: { relation: 'and', items: [{ key: 'isEdit', value: [false], relation: ['='] }] },
              },
            },
            {
              title: '编辑',
              onClick: (record, index) => this.editChildRow(record),
              rules: {
                hide: { relation: 'and', items: [{ key: 'isEdit', value: [true], relation: ['='] }] },
              },
            },
            {
              title: '删除',
              onClick: (record, index) => this.deleteChildRow(record),
              rules: {
                hide: { relation: 'and', items: [{ key: 'isEdit', value: [true], relation: ['='] }] },
              },
            },
          ],
        });
      }
    }
    return columns;
  };

  // 子表的取消
  cancelChildRow = (record) => {
    const { dataSource, currentRow } = this.state;
    const { tradeInfo } = this.props;
    dataSource.map((item) => {
      if (item.key == record.pid) {
        item.isEdit = false;
        item.nestedConfig.dataSource = currentRow ? [...currentRow.nestedConfig.dataSource] : item.nestedConfig.dataSource.filter((item) => !item.isEdit);
        item.tradePrice = 0;
        item.fee = 0; // 将该行的费用和 交易金额清0  后面重新计算
        const arr = item.nestedConfig.dataSource;
        item.nestedConfig.dataSource = [...arr];
        let myTradePriceSum = 0; // 父节点的【交易金额】等于子节点【交易金额】总和；
        item.nestedConfig.dataSource.map((child) => {
          // 对应的其他属性
          myTradePriceSum += child.tradePrice;
          item.tradePrice = myTradePriceSum;
          if (tradeInfo.fee && tradeInfo.repurchaseAmount) {
            // 费用（表格中组合费用）】= 交易金额（组合）/回购金额*费用（交易信息中的总费用），
            item.fee = (item.tradePrice / (tradeInfo.repurchaseAmount || 0)) * tradeInfo.fee;
            item.fee = Number(item.fee.toFixed(2));
          }
        });
      }
    });
    this.setState(
      {
        editFlag: false,
        dataSource: [...dataSource],
      },
      () => {
        this.calcAssign(); // 重新计算比例
      },
    );
  };

  // 编辑子表行
  editChildRow = (record) => {
    const { dataSource, editFlag } = this.state;
    if (editFlag) {
      message.warning('每次只能编辑一条数据！');
      return;
    }
    let obj;

    dataSource.map((item) => {
      if (item.key == record.pid) {
        obj = _.cloneDeep(item);
        const arr=item.nestedConfig.dataSource
        arr.map((child) => {
          if (child.key == record.key) {
            child.isEdit = true;
          }
        });
        item.nestedConfig = { columns: this.childColumns() };
        item.nestedConfig.dataSource=JSON.parse(JSON.stringify(arr))
        this.setState({ currentRow: obj, editFlag: true });
      }
    });
  };

  // 取消行 父表只有新增行 取消即删除
  cancelRow = (key) => {
    const { dataSource, currentRow } = this.state;
    if (!currentRow) {
      // 新增的取消
      const arr = dataSource.filter((item) => item.isEdit != true);
      this.setState(
        {
          dataSource: [...arr],
          editFlag: false,
        },
        () => {
          this.calcAssign(); // 重新计算
        },
      );
      
    }
  };

  // 删除父表行
  deleteRow = (key) => {
    const { dataSource, currentRow } = this.state;
    const data = dataSource.filter((item) => item.key != key);
    const arr = data.filter((item) => item.isEdit);
    this.setState(
      {
        dataSource: [...data],
        currentRow: arr.length ? currentRow : undefined, // 注意编辑状态的影响
        editFlag: !!arr.length,
      },
      () => {
        this.calcAssign(); // 重新计算
      },
    );
  };

  // 删除子表行
  deleteChildRow = (record) => {
    const { dataSource } = this.state;
    const { tradeInfo } = this.props;
    dataSource.map((item) => {
      if (item.key == record.pid) {
        item.tradePrice = 0;
        item.fee = 0; // 将该行的费用和 交易金额清0  后面重新计算
        const arr = item.nestedConfig.dataSource.filter((child) => child.key != record.key);
        item.nestedConfig.dataSource = [...arr];
        let myTradePriceSum = 0; // 父节点的【交易金额】等于子节点【交易金额】总和；
        item.nestedConfig.dataSource.map((child) => {
          // 对应的其他属性
          myTradePriceSum += child.tradePrice;
          item.tradePrice = myTradePriceSum;
          if (tradeInfo.fee && tradeInfo.repurchaseAmount) {
            // 费用（表格中组合费用）】= 交易金额（组合）/回购金额*费用（交易信息中的总费用），
            item.fee = (item.tradePrice / (tradeInfo.repurchaseAmount || 0)) * tradeInfo.fee;
            item.fee = Number(item.fee.toFixed(2));
          }
        });
      }
    });
    this.setState(
      {
        dataSource: [...dataSource],
      },
      () => {
        this.calcAssign(); // 重新计算
      },
    );
  };

  // 新增父表行
  addNew = () => {
    const { dataSource, expandedKeys } = this.state;
    this.setState({
      currentRow: undefined,
      editFlag: true,
    });
    if (this.props.tradeInfo.direction == 1) this.getChildTable('add');
    if (this.props.tradeInfo.direction == 2) {
      const obj = {
        isEdit: true,
        key: uuid(32),
        tradeNum: 0,
        tradePrice: 0,
        nestedConfig: { columns: this.childColumns(), dataSource: [] },
      };
      dataSource.unshift(obj);
      expandedKeys.push(obj.key); // 展开行设置
      this.setState({ dataSource: [...dataSource], expandedKeys: [...expandedKeys] });
    }
  };

  // 批量删除 父表数据
  delBatch = () => {
    const { dataSource, selectedRowKeys, currentRow } = this.state;
    for (let i = 0; i < selectedRowKeys.length; i++) {
      for (let j = 0; j < dataSource.length; j++) {
        if (selectedRowKeys[i] == dataSource[j].key) {
          dataSource.splice(j, 1);
        }
      }
    }
    const arr = dataSource.filter((item) => item.isEdit == true);
    this.setState(
      {
        dataSource: [...dataSource],
        currentRow: arr.length ? currentRow : undefined, // 注意编辑状态的影响
        editFlag: !!arr.length,
        selectedRowKeys: [],
      },
      () => {
        this.calcAssign(); // 重新计算
      },
    );
  };

  // 保存父表行数据
  saveRow = (record) => {
    const { dataSource } = this.state;
    if (!record.productId) {
      message.warning('请选择产品组合');
      return;
    }
    // 校验是否有重复产品组合id
    const arr = dataSource.map((item) => item.productId);
    if (isRepeat(arr)) {
      message.warning('该行的产品组合与其他行重复');
      return;
    }
    // 保存对应数据，去掉编辑状态
    dataSource.map((item) => {
      if (item.key == record.key) {
        item.isEdit = false;
        item.isAdd = false;
      }
    });
    this.setState({
      dataSource: [...dataSource],
      editFlag: false,
      currentRow: undefined,
    });
  };

  // 保存行
  saveChildRow = (record) => {
    const { dataSource } = this.state;
    const { tradeInfo } = this.props;
    if (!record.id) {
      message.warning('请选择质押券');
      return;
    }
    // 校验是否有重复质押券
    const arr = [];
    dataSource.map((item) => {
      if (item.key == record.pid) {
        item.nestedConfig.dataSource.map((child) => {
          arr.push(child.id);
        });
      }
    });
    if (isRepeat(arr)) {
      message.warning('质押券在同一个子表格中不可重复');
      return;
    }
    /**
         * 银行间质押式回购交易方向支持：融资回购和融券回购，其中，融券回购时要验资，融资回购时要验券。
            验资：组合下各质押券的【交易金额】与组合的【T+0可用】或【T+1可用】对比（看清算速度）
            验券：各质押券的【交易数量】与【可用数量】对比。
         */
    if (record.tradeNum > (record.pledgeAmount || 0)) {
      message.warning('交易数量不能大于当前行的质押数量');
      return;
    }
    if (tradeInfo.direction == '1') {
      // 融券回购时要验资
      for (let index = 0; index < dataSource.length; index++) {
        const item = dataSource[index];
        if (item.key == record.pid) {
          if (tradeInfo.settlementSpeed == 1) {
            // t0
            if (record.tradePrice > (item.t0 || 1000)) {
              message.warning('交易金额不能大于T+0可用');
              return;
            }
          } else if (record.tradePrice > (item.t1 || 0)) {
              message.warning('交易金额不能大于T+1可用');
              return;
            }
        }
      }
    } else {
      // 融资回购时要验券
      if (record.tradeNum > (record.available || 0)) {
        message.warning('交易数量不能大于可用数量');
        return;
      }
    }
    // 保存对应数据，去掉编辑状态
    dataSource.map((item) => {
      if (item.key == record.pid) {

        item.nestedConfig.dataSource.map((child) => {
          child.isEdit = false;
          child.isAdd = false;
        });
        item.nestedConfig.columns=this.childColumns();
      }
    });
    this.setState(
      {
        dataSource: [...dataSource],
        editFlag: false,
        currentRow: undefined,
      },
      () => {
        this.calcAssign(); // 计算比例
      },
    );
  };

  // 查询资金
  queryFund = (productId, record) => {
    const { tradeInfo, dispatch } = this.props;
    const query = {};
    dispatch({
      type: 'availableAssetM/getFund',
      payload: {
        nodeId: productId,
        maatApi: !!isZiGuanEvir(),
      },
      callback: (data) => {
        if (data && data.length) {
          const { toneAvailableFund, tzeroAvailableFund } = data[0];
          query.t0 = tzeroAvailableFund;
          query.t1 = toneAvailableFund;
        } else {
          query.t0 = undefined;
          query.t1 = undefined;
        }
        this.modifyDatas(query, record); // 修改表格中的值
      },
    });
  };

  // 查询持仓
  queryPosition = (productId, tradingcode, record) => {
    const { tradeInfo, dispatch } = this.props;
    const { dataSource } = this.state;
    const query = {};
    dispatch({
      type: 'tradeHoldM/getPosition',
      payload: {
        tradingcode,
        exchangecode: tradeInfo.exchangecode,
        fundId: productId,
        maatApi: !!isZiGuanEvir(),
      },
      callback: (data) => {
        if (data && !(parseFloat(data.availableAmount).toString() == 'NaN') && !(parseFloat(data.currentAmount).toString() == 'NaN')) {
          const { availableAmount, currentAmount } = data;
          query.available = availableAmount;
          query.hold = currentAmount;
        } else {
          query.available = undefined;
          query.hold = undefined;
        }
        dataSource.map((x) => {
          if (x.key == record.pid) {
            x.nestedConfig.dataSource.map((item) => {
              // 对应的其他属性
              if (item.key == record.key) {
                item.available = query.available;
                item.hold = query.hold;
              }
            });
          }
        });
        this.setState({
          dataSource: [...dataSource],
        });
      },
    });
  };

  // 替换表格中的可用资金
  modifyDatas = (obj, record) => {
    const { dataSource } = this.state;
    dataSource.map((item) => {
      if (item.key == record.key) {
        item.t0 = obj.t0;
        item.t1 = obj.t1;
      }
    });
    this.setState({
      dataSource: [...dataSource],
    });
  };

  // 交易信息下的质押券表格
  renderTradeTable = () => {
    const { tradeInfoDs } = this.state;
    const columns = [
      {
        title: '质押券',
        key: 'name',
        ellipsis: true,
        render: (text, record) => {
          return `${record.tradingcode  }-${  record.secuabbr}`;
        },
      },
      { title: '质押数量', key: 'pledgeAmount', type: 'number', width: 160 },
      {
        title: '折算率',
        key: 'pledgeRatio',
        align: 'right',
        render: (text, record) => {
          if (text === undefined || text === null) return '--';
          return `${(Number(text)).toFixed(2)  }%`;
        },
      },
      { title: '券面金额', key: 'valuationPrice', type: 'money' },
      { title: '成交金额', key: 'denomination', type: 'money' },
      {
        title: '已分配比例',
        key: 'assignRatio',
        render: (text, record) => {
          return (
            <span>
              {record.ratio}
              <span style={{ margin: '0 6px' }}>({`${fixedNum(record.assignAmount, 0)}/${fixedNum(parseInt(Number(record.pledgeAmount), 0))}`})</span>
            </span>
          );
        },
      },
    ];
    columns.map((item) => {
      if (item.key !== 'name') item.width = `${82 / (columns.length - 1)  }%`;
    });
    return (
      <div>
        <TableC columns={columns} dataSource={tradeInfoDs} hidePage={true} scroll={{ y: 240 }} rowKey='id' />
      </div>
    );
  };

  render() {
    const { editFlag, selectedRowKeys } = this.state;
    return (
      <div>
        {this.renderTradeTable()}
        <div className={myStyle.borderTop}>
          <FirstHeaderC title='手工拆分' />
        </div>
        <div className={myStyle.addBtn1}>
          {!this.props.isDetail && (
            <>
              <PrimaryC title='新增' disabled={editFlag == true || this.props.loadingStatus == true} onClick={this.addNew} />
              <Popconfirm title={'确定删除？'} icon={<ExclamationCircleOutlined />} onConfirm={this.delBatch}>
                <PrimaryGhostC title='批量删除' disabled={selectedRowKeys.length == false} />
              </Popconfirm>
            </>
          )}
        </div>
        {this.renderTable()}
      </div>
    );
  }
}
export default connect(({ orderSplitM, tradeHoldM, availableAssetM, loading }) => ({
  orderSplitM,
  tradeHoldM,
  availableAssetM,
  loading,
}))(SplitTableBankC);
